package com.plus.config;


import cn.hutool.extra.servlet.ServletUtil;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @program: plus-easy
 * @ClassName ApiSignInterceptor
 * @description:ip过滤器
 * @author: AI
 * @create: 2024-01-23 14:58
 * @Version 1.0
 **/
@Component
@ConfigurationProperties(prefix = "spring.security.ip")
public class IPInterceptor implements HandlerInterceptor {

    /**
     * 是否启用
     */
    private static String mode;
    public void setMode(String mode) {
        this.mode = mode;
    }

    /**
     * 白名单列表
     */
    private static List<String> whites;
    public void setWhites(List<String> whites) {
        this.whites = whites;
    }

    /**
     * 黑名单列表
     */
    private static List<String> blanks;
    public void setBlanks(List<String> blanks) {
        this.blanks = blanks;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //处理跨域问题
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST,PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");

        String httpIp = ServletUtil.getClientIP(request, null);
        if (StringUtils.isEmpty(httpIp)) {
            response.sendError(404);
            return false;
        }

        boolean valid = false;
        //过滤ip
        String[] httpIps = httpIp.split(",");
        if("whiteed".equals(mode)){
            valid = false;
            Integer size = whites.size();
            for(String httpip : httpIps){
                for(int i=0; i< size; i++){
                    if(whites.get(i).equals(httpip.trim())){
                        valid = true;
                        break;
                    }
                }
            }
        }else {
            valid = true;
            Integer size = blanks.size();
            for(String httpip : httpIps){
                for(int i=0; i< size; i++){
                    if(blanks.get(i).equals(httpip.trim())){
                        valid = false;
                        break;
                    }
                }
            }
        }


        if (!valid) {
            response.sendError(404);
            return  false;
        }
        return  true;
    }

}
